package com.snail.snailvr.model;

import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.alibaba.fastjson.annotation.JSONField;
import com.snail.snailvr.VRApp;
import com.snail.snailvr.network.providers.downloads.DownloadManager;
import com.snail.snailvr.network.providers.downloads.DownloadHelper;
import com.snail.snailvr.utils.FileUtil;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.Util;

/**
 * Video类 所有视频列表基类
 * Created by snail on 16/4/15.
 */
@Table(name = "download_lists")
public class VideoInfo extends Model implements Parcelable {
    public static final String COLUMN_DOWNLOAD_BEGIN ="download_begin_time";
    public static final String COLUMN_VIDEO_ID = "video_id";
    private StringBuilder mStringBuilder = new StringBuilder();
    private String mStringVideoSize;
    private MediaMetadataRetriever mMediaRetriever;
    //对应TaskId以及Download id
    @Column(name = COLUMN_VIDEO_ID, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    private long videoId;
    @Column(name = COLUMN_DOWNLOAD_BEGIN)
    private long downloadBeginTime;//下载完成时间 用于首页的排序
    @Column(name = "video_name")
    private String videoName;
    @Column(name = "video_icon")
    private String icon;
    @Column(name = "video_path")
    private String videoPath;
    @Column(name = "video_leble")
    private String videoLeble;
    @Column(name = "video_size")
    private long videoSize;
    @Column(name = "downloaded_size")
    private long downloadedSize;
    @Column(name = "video_duration")
    private long duration;
    @Column(name = "format_duration")
    private String formatDuration;
    @Column(name = "download_percent")
    private int downloadedPercent;//已下载进度
    @Column(name = "download_status")
    private int downloadState=DownloadManager.STATUS_INIT;//应用下载状态
    @Column(name = "reason")
    private int reason;
    @Column(name = "link_media")
    private boolean isLinkedToMedia;
    @Column(name = "demo_video")
    private boolean demoVideo;
    @Column(name = "new_video")
    private boolean newVideo=true;//新增还未播放的视频


    private boolean isDownloadByDownloadManager=true;//是否是用自带的下载器下载的否则是wifi传输或者网盘下载

    private String downloadSpeed = DownloadHelper.DEFAULT_DOWNLOAD_SPEED;//下载速度

    public int getDownloadedPercent() {
        return downloadedPercent;
    }

    public void setDownloadedPercent(int downloadedPercent) {
        if(downloadedPercent>=this.downloadedPercent)
            this.downloadedPercent = downloadedPercent;
    }

    public long getVideoId() {
        return videoId;
    }

    public void setVideoId(long videoId) {
        this.videoId = videoId;
    }

    public long getDownloadBeginTime() {
        return downloadBeginTime;
    }

    public void setDownloadBeginTime(long downloadBeginTime) {
        this.downloadBeginTime = downloadBeginTime;
    }

    public String getVideoName() {
        return videoName;
    }

    public void setVideoName(String videoName) {
        this.videoName = videoName;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getVideoPath() {
        return videoPath;
    }

    public void setVideoPath(String videoPath) {
        this.videoPath = FileUtil.addFileToPath(videoPath);
    }

    public String getVideoLeble() {
        return videoLeble;
    }

    public void setVideoLeble(String videoLeble) {
        this.videoLeble = videoLeble;
    }

    public long getVideoSize() {
        return videoSize;
    }

    public void setVideoSize(long videoSize) {
        this.videoSize = videoSize;
        this.mStringVideoSize = FileUtil.formatFileSize(VRApp.getInstance(), videoSize);
    }

    public long getDownloadedSize() {
        return downloadedSize;
    }

    public void setDownloadedSize(long downloadedSize) {
        this.downloadedSize = downloadedSize;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public int getDownloadState() {
        return downloadState;
    }

    public void setDownloadState(int downloadState) {
        this.downloadState = downloadState;
    }

    public int getReason() {
        return reason;
    }

    public void setReason(int reason) {
        this.reason = reason;
    }

    public boolean isLinkedToMedia() {
        return isLinkedToMedia;
    }

    public void setLinkedToMedia(boolean linkedToMedia) {
        isLinkedToMedia = linkedToMedia;
    }

    public String getDownloadSpeed() {
        return downloadSpeed;
    }

    public void setDownloadSpeed(String downloadSpeed) {
        this.downloadSpeed = downloadSpeed;
    }

    public String getDownloadSpeedAndPercent() {
        mStringBuilder.delete(0, mStringBuilder.length());
        return mStringBuilder.append(downloadSpeed).append("/S").append(", ").append(downloadedPercent).append("%").toString();
    }

    public void lintToMeida(Context context, String filePath) {
        //filename是我们的文件全名，包括后缀哦
        if (!isLinkedToMedia) {
            FileUtil.refreshMediaStore(filePath);
            isLinkedToMedia = true;
        }
    }

    public boolean isDemoVideo() {
        return demoVideo;
    }

    public void setDemoVideo(boolean demoVideo) {
        this.demoVideo = demoVideo;
    }

    public void setFormatDuration(String formatDuration) {
        this.formatDuration = formatDuration;
    }

    //TODO 耗时操作 需要优化 有几率会获取不到
    public String getFormatDuration() {
        if (downloadedSize>=videoSize&&downloadState== DownloadManager.STATUS_SUCCESSFUL&&formatDuration == null && videoPath != null) {

            String path = FileUtil.getRealFilePath(videoPath);
            LogUtils.d("getFormatDuration"+path);
            try {
                mMediaRetriever = new MediaMetadataRetriever();
                mMediaRetriever.setDataSource(path);
                String duration=mMediaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                if(duration!=null&& TextUtils.isDigitsOnly(duration))
                    formatDuration = Util.getDuration(Long.parseLong(duration)); // 播放时长单位为毫秒
            } catch (Exception e) {
                LogUtils.e("format duration exception="+e.toString());
            }

        }
        return formatDuration;
    }

    public void releaseMediaRetriever(){
        if(mMediaRetriever!=null)
            mMediaRetriever.release();
    }
    public String getStringVideoSize() {
        if(mStringVideoSize==null)
            mStringVideoSize = FileUtil.formatFileSize(VRApp.getInstance(), this.videoSize);
        return mStringVideoSize;
    }

    public boolean isDownloadByDownloadManager() {
        return isDownloadByDownloadManager;
    }

    public void setDownloadByDownloadManager(boolean downloadByDownloadManager) {
        isDownloadByDownloadManager = downloadByDownloadManager;
    }

    public boolean isNewVideo() {
        return newVideo;
    }

    public void setNewVideo(boolean newVideo) {
        this.newVideo = newVideo;
    }

    public VideoInfo() {
    }

    /****************************** 以下字段用于发现页面 *******************/
    private int IBannerId; // ID
    private int cType;   //1-直播 ,2-视频
    private String SName; // 名称
    private String CPicUrl; // 图片地址
    private String CVideoUrl; // 在线播放视频地址
    private String CDownloadUrl; // 下载地址
    private String CFileSize; // 视频大小
    private Integer ISortValue; // 排序
    private String DUpdate; // 更新时间
    private String DCreate; // 创建时间
    private String SDate; // 格式化过的更新时间，例如：06/17/2016
    private String SVideoLength; // 格式化过的视频时长，例如：01:20:03

    public int getIBannerId() {
        return IBannerId;
    }
    @JSONField(name = "IBannerId")
    public void setIBannerId(int IBannerId) {
        this.IBannerId = IBannerId;
    }

    public int getcType() {
        return cType;
    }
    @JSONField(name = "cType")
    public void setcType(int cType) {
        this.cType = cType;
    }

    public String getSName() {
        return SName;
    }
    @JSONField(name = "SName")
    public void setSName(String SName) {
        this.SName = SName;
    }

    public String getCPicUrl() {
        return CPicUrl;
    }
    @JSONField(name = "CPicUrl")
    public void setCPicUrl(String CPicUrl) {
        this.CPicUrl = CPicUrl;
    }

    public String getCVideoUrl() {
        return CVideoUrl;
    }
    @JSONField(name = "CVideoUrl")
    public void setCVideoUrl(String CVideoUrl) {
        this.CVideoUrl = CVideoUrl;
    }

    public String getCDownloadUrl() {
        return CDownloadUrl;
    }
    @JSONField(name = "CDownloadUrl")
    public void setCDownloadUrl(String CDownloadUrl) {
        this.CDownloadUrl = CDownloadUrl;
    }
    @JSONField(name = "CFileSize")
    public String getCFileSize() {
        return CFileSize;
    }

    public void setCFileSize(String CFileSize) {
        this.CFileSize = CFileSize;
    }

    public Integer getISortValue() {
        return ISortValue;
    }
    @JSONField(name = "ISortValue")
    public void setISortValue(Integer ISortValue) {
        this.ISortValue = ISortValue;
    }

    public String getDUpdate() {
        return DUpdate;
    }
    @JSONField(name = "DUpdate")
    public void setDUpdate(String DUpdate) {
        this.DUpdate = DUpdate;
    }

    public String getDCreate() {
        return DCreate;
    }
    @JSONField(name = "DCreate")
    public void setDCreate(String DCreate) {
        this.DCreate = DCreate;
    }

    public String getSDate() {
        return SDate;
    }
    @JSONField(name = "SDate")
    public void setSDate(String SDate) {
        this.SDate = SDate;
    }

    public String getSVideoLength() {
        return SVideoLength;
    }
    @JSONField(name = "SVideoLength")
    public void setSVideoLength(String SVideoLength) {
        this.SVideoLength = SVideoLength;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.mStringVideoSize);
        dest.writeLong(this.videoId);
        dest.writeLong(this.downloadBeginTime);
        dest.writeString(this.videoName);
        dest.writeString(this.icon);
        dest.writeString(this.videoPath);
        dest.writeString(this.videoLeble);
        dest.writeLong(this.videoSize);
        dest.writeLong(this.downloadedSize);
        dest.writeLong(this.duration);
        dest.writeString(this.formatDuration);
        dest.writeInt(this.downloadedPercent);
        dest.writeInt(this.downloadState);
        dest.writeInt(this.reason);
        dest.writeByte(this.isLinkedToMedia ? (byte) 1 : (byte) 0);
        dest.writeByte(this.demoVideo ? (byte) 1 : (byte) 0);
        dest.writeByte(this.newVideo ? (byte) 1 : (byte) 0);
        dest.writeByte(this.isDownloadByDownloadManager ? (byte) 1 : (byte) 0);
        dest.writeString(this.downloadSpeed);
        dest.writeInt(this.IBannerId);
        dest.writeInt(this.cType);
        dest.writeString(this.SName);
        dest.writeString(this.CPicUrl);
        dest.writeString(this.CVideoUrl);
        dest.writeValue(this.ISortValue);
        dest.writeString(this.DUpdate);
        dest.writeString(this.DCreate);
        dest.writeString(this.SDate);
        dest.writeString(this.SVideoLength);
    }

    protected VideoInfo(Parcel in) {
        this.mStringVideoSize = in.readString();
        this.videoId = in.readLong();
        this.downloadBeginTime = in.readLong();
        this.videoName = in.readString();
        this.icon = in.readString();
        this.videoPath = in.readString();
        this.videoLeble = in.readString();
        this.videoSize = in.readLong();
        this.downloadedSize = in.readLong();
        this.duration = in.readLong();
        this.formatDuration = in.readString();
        this.downloadedPercent = in.readInt();
        this.downloadState = in.readInt();
        this.reason = in.readInt();
        this.isLinkedToMedia = in.readByte() != 0;
        this.demoVideo = in.readByte() != 0;
        this.newVideo = in.readByte() != 0;
        this.isDownloadByDownloadManager = in.readByte() != 0;
        this.downloadSpeed = in.readString();
        this.IBannerId = in.readInt();
        this.cType = in.readInt();
        this.SName = in.readString();
        this.CPicUrl = in.readString();
        this.CVideoUrl = in.readString();
        this.ISortValue = (Integer) in.readValue(Integer.class.getClassLoader());
        this.DUpdate = in.readString();
        this.DCreate = in.readString();
        this.SDate = in.readString();
        this.SVideoLength = in.readString();
    }

    public static final Creator<VideoInfo> CREATOR = new Creator<VideoInfo>() {
        @Override
        public VideoInfo createFromParcel(Parcel source) {
            return new VideoInfo(source);
        }

        @Override
        public VideoInfo[] newArray(int size) {
            return new VideoInfo[size];
        }
    };
}
